<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas{
      background-image: url("./img/001.jpg");
      background-size: cover;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="400" height="400"></canvas>
  <button class="cu">粗线条</button>
  <button class="xi">细线条</button>
  <button class="baocun">保存图片</button>
  <!-- <button>颜色</button> -->
  <input type="color" name="" id="" class="color">
  <button class="xp">橡皮擦</button>
  <button class="clean">清空画布</button>
  <script>
    /** @type {HTMLCanvasElement} */
    var canvas=document.querySelector("#canvas")
    var ctx=canvas.getContext("2d")
    ctx.lineWidth=10
    ctx.strokeStyle="skyblue"
    ctx.lineCap="round"
    ctx.lineJoin="round"
    var se=false
    canvas.onmousedown=function(){
      ctx.beginPath()
      se=true
    }
    var x,y;
    canvas.onmousemove=function(e){
      if(se){
      x=e.pageX
      y=e.pageY
      ht(x,y)
      }
      
    }
    canvas.onmouseup=function(){
      // ctx.closePath()
      ctx.closePath()
      se=false

    }
    function ht(x,y){
      // ctx.beginPath()
      ctx.lineTo(x,y)
      ctx.stroke()
      // ctx.closePath()
    }
    var color=document.querySelector(".color")
    var cu=document.querySelector(".cu")
    var xi=document.querySelector(".xi")
    var xp=document.querySelector(".xp")
    var clean=document.querySelector(".clean")
    var baocun=document.querySelector(".baocun")
    color.onchange=function(){
      ctx.strokeStyle=color.value
      // console.log(color.value);
    }
    cu.onclick=function(){
      ctx.restore()
      ctx.lineWidth=20
      ctx.save()
    }
    xi.onclick=function(){
      ctx.restore()
      ctx.lineWidth=2
      ctx.save()
    }
    xp.onclick=function(e){
      // console.log(x);
      //  var xx=e.pageX
      // console.log(xx);
     
      // var yy=e.pageY
      ctx.globalCompositeOperation = "destination-out"
      // canvas.onmousemove=function(e){
        ctx.lineWidth=10
      ctx.arc(x,y,10,0,Math.PI*2)
      // ctx.fill()
      // }
      
    }
    clean.onclick=function(){
      ctx.clearRect(0,0,400,400)
    }

    baocun.onclick=function(){
      // 1.
      // var urlData=canvas.toDataURL()
      // var imga=document.createElement("a")
      // imga.setAttribute("download","厉害吧")
      // imga.href=urlData
      // imga.click()

      // 2.
      const el = document.createElement('a');
  // 设置 href 为图片经过 base64 编码后的字符串，默认为 png 格式
  el.href = canvas.toDataURL();
  el.download = 'acc';
  
  // 创建一个点击事件并对 a 标签进行触发
  const event = new MouseEvent('click');
  el.dispatchEvent(event);
    }
    // console.log(color);
  </script>
</body>
</html>